<?php

use Fox\SalesDistribution\Sales;
use Custom\Control;
use Doctrine\DBAL\Types\Type;
$approved = Xview::instance()->val("approved");

if($approved)
{
	try {
		$today = new DateTime();
		$today->sub(new DateInterval("P1M"));
		$formated = $today->format("Y-m");
		$date = new DateTime($formated."-01");
		$finder = new Control();
		$res = $finder->find(new Fox\Dao\SqlFragment("uname = ? AND cdate = ? ",
									array(User::current()->getId(),
											$date),
									array(Type::INTEGER,Type::DATE)),
							array("date" => "DESC"),
							null,
							1);
		if(count($res) > 0)
		{
			echo Fox\Message::Information( Msg(Sales::BUNDLE_NAME,34,$today->format("m"),$today->format("Y")));
		}	
		else
		{
			$cdate = new DateTime();
			$control = new Control();
			$control->setFields(array("uname" => User::current()->getId(),
									  "date" => $date->format("Y-m-d"),
									  "cdate" => $cdate->format(Control::CORE_SQL_DATETIME_FORMAT)));
			$control->create();
			echo Fox\Message::Success( Msg(Sales::BUNDLE_NAME,35,$today->format("m"),$today->format("Y")));
		}	
	}
	catch (Fox\Object\Exception\Save $e)
	{
		echo Fox\Message::Error($e->getMessage());
	}
}